import axios from 'axios'
import Util from '@/assets/js/util'
import Storage from '@/assets/js/storage'

// import Config from '@/plugins/auth-client/utils/config'

// axios实例
export const service = axios.create(
  {
    baseURL: import.meta.env.VITE_DOMAIN_PATH,
    timeout: 50000,
    headers: { 'Content-Type': 'application/json;charset=utf-8' }
  }
)

export const init = (app, router) => {
  // 获取当前url地址
  const url = window.location.protocol + '//' + window.location.host
  Storage.session('locationUrl', url)

  // 配置 OAuth2.0
  // app.config.globalProperties.$auth.config.appId = 'vue'
  // app.config.globalProperties.$auth.config.appSecret = '123456'
  // Vue.prototype.$auth.config.grant_type = 'password'

  // 设置后台请求地址前缀
  // Vue.axios.defaults.baseURL = process.env.SERVER_URL
  // Vue.prototype.$auth.config.baseUrl = process.env.BASE_URL
  // Vue.prototype.$auth.config.authUrl = process.env.AUTH_URL

  // build后配置
  // Vue.axios.defaults.baseURL = window.serverconf[process.env.NODE_ENV]['baseURL']
  // Vue.prototype.$auth.config.baseUrl = window.serverconf[process.env.NODE_ENV]['baseUrl']
  // Vue.prototype.$auth.config.authUrl = window.serverconf[process.env.NODE_ENV]['authUrl']
  // app.axios.defaults.baseURL = ''
  // app.config.globalProperties.$auth.config.baseUrl = Storage.get('locationUrl') + '/manage-web-static'
  // if (__DEV__) {
  //   app.config.globalProperties.$auth.config.authUrl = import.meta.env.VITE_DOMAIN_PATH + '/op-admin-oauth'
  // } else {
  //   app.config.globalProperties.$auth.config.authUrl = Storage.get('locationUrl') + '/op-admin-oauth'
  // }

  // 拦截请求
  service.interceptors.request.use(config => {
    // 这里做些配置
    if (config.headers['Content-Type'] === undefined) {
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
      // json -> form data
      config['transformRequest'] = [(data) => {
        return Util.jsonToString(data)
      }]
    }
    // if (config && config.url && config.url.indexOf('/oauth/token') < 0) {
    //   config.headers['Authorization'] = 'Bearer ' + app.config.globalProperties.$auth.token()
    // }
    config.headers['Accept-Language'] = 'zh-CN' // 先传中文
    // 配置请求头部信息
    config.headers['manage_user_id'] = 'manage-web-static'
    config.headers['USERID'] = Storage.get('userId')
    config.headers['TOKEN'] = Storage.get('token')
    return config
  }, error => {
    Promise.reject(error)
  })

  // 拦截响应
  service.interceptors.response.use(response => {
    // oauth鉴权返回处理
    if (response && response.config && response.config.url && response.config.url.indexOf('/oauth/token') >= 0) {
      return response
    } else if (response && response.config && response.config.url && response.config.url.indexOf('platform/op-user-manage/api/v2/orgs/') >= 0) {
      return Object.assign({
        success: true
      }, response)
    } else {
      if (Object.is(response.data.state, 'OK')) {
        return Object.assign({ success: true }, response)
      }
      return Object.assign({ success: false }, response)
    }
  }, error => {
    if (error.response && Object.is(error.response.status, 401)) {
      let parentUrl
      // 在无界里面子工程需要 window.parent?.location?.href
      if(window.parent?.location?.href) {
        parentUrl = window.parent.location.href.split('?')?.[0]
      }
      const currentUrl = parentUrl || window.location.href
      // const redirectUri = currentUrl.indexOf('/unauthorize') > -1 ? Storage.get('beforeAnauthorizePage') : currentUrl
      // const url = Config.authUrl + '/oauth/authorize?response_type=code&client_id=' + Config.appId + '&redirect_uri=' + redirectUri + '&code_challenge_method=S256&code_challenge=' + Util.setSha256(Config.code)
      const url = window.origin + '/manage-web-static/login?redirect=' + encodeURIComponent(currentUrl)
      if(window.parent?.location?.href) {
        window.parent.location.href = url
      } else {
        window.location.href = url
      }
      Object.assign(error, {
        errorMessage: '用户登录状态已失效，请重新登录！'
      })
      return Promise.reject(error)
    }
    if (error && error.response && error.response.data && error.response.data.message) {
      Object.assign(error, {
        errorMessage: error.response.data.message
      })
    } else if (Util.isEmpty(error.message)) {
      Object.assign(error, {
        errorMessage: '好像遇到点问题，请刷新或稍后再试'
      })
    } else {
      Object.assign(error, {
        errorMessage: error.message
      })
    }
    return Promise.reject(error)
  })
}
